import { validatenull } from 'src/util/validate';
// import { LocalStorage, SessionStorage } from 'quasar'

let SessionStorage = window.sessionStorage
let LocalStorage = window.localStorage

export const setStore = (params) => {
  let {
    name,
    content,
    type
  } = params;
  let obj = {
    dataType: typeof (content),
    content: content,
    type: type,
    datetime: new Date().getTime()
  }
  if (type) {
    SessionStorage.setItem(name, obj.content);
  } else {
    LocalStorage.setItem(name, obj.content);
  }
}

export const getStore = (params) => {
  let {
    name,
    debug
  } = params;
  let obj = {},
    content;
  obj = sessionStorage.getItem(name);

  if (validatenull(obj)) obj = LocalStorage.getItem(name);
  if (validatenull(obj)) return;
  try {
    obj = JSON.parse(obj);
  } catch (e) {
    return obj;
  }
  if (debug) {
    return obj;
  }
  if (obj.dataType === 'string') {
    content = obj.content;
  } else if (obj.dataType === 'number') {
    content = Number(obj.content);
  } else if (obj.dataType === 'boolean') {
    content = evil(obj.content);
  } else if (obj.dataType === 'object') {
    content = obj.content;
  }
  return content;
}

/**
 * 获取全部localStorage
 */
export const getAllStore = (params) => {
  let list = [];
  let {
    type
  } = params;
  if (type) {
    for (let i = 0; i <= SessionStorage.length; i++) {
      list.push({
        name: SessionStorage.key(i),
        content: getStore({
          name: SessionStorage.key(i),
          type: 'session'
        })
      })
    }
  } else {
    for (let i = 0; i <= LocalStorage.length; i++) {
      list.push({
        name: LocalStorage.key(i),
        content: getStore({
          name: LocalStorage.key(i)
        })
      })
    }
  }
  return list;
}

/**
 * 清空全部localStorage
 */
export const clearStore = (params) => {
  let {
    type
  } = params;
  if (type) {
    SessionStorage.clear();
  } else {
    LocalStorage.clear()
  }
}

export const evil = (fn) => {
  let Fn = Function;
  return new Fn('return ' + fn)();
}
